package top.heliming.youyou.item.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import top.heliming.youyou.common.enums.ExceptionEnum;
import top.heliming.youyou.common.exception.LyException;
import top.heliming.youyou.common.pojo.PageResult;
import top.heliming.youyou.item.dao.BrandMapper;
import top.heliming.youyou.item.dao.SkuMapper;
import top.heliming.youyou.item.dao.SpuDetailMapper;
import top.heliming.youyou.item.dao.SpuMapper;
import top.heliming.youyou.item.dao.StockMapper;
import top.heliming.youyou.item.pojo.Brand;
import top.heliming.youyou.item.pojo.Sku;
import top.heliming.youyou.item.pojo.Spu;
import top.heliming.youyou.item.pojo.SpuBo;
import top.heliming.youyou.item.pojo.SpuDetail;
import top.heliming.youyou.item.pojo.Stock;
import top.heliming.youyou.item.service.CategoryService;
import top.heliming.youyou.item.service.GoodsService;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/05/30 下午 11:40
 */
@Service
public class GoodsServiceImpl implements GoodsService {

  private static final Logger LOGGER = LoggerFactory.getLogger(GoodsServiceImpl.class);

  @Autowired
  private SpuMapper spuMapper;

  @Autowired
  private CategoryService categoryService;

  @Autowired
  private BrandMapper brandMapper;
  @Autowired
  private SpuDetailMapper spuDetailMapper;
  @Autowired
  private StockMapper stockMapper;
  @Autowired
  private SkuMapper skuMapper;

  @Autowired
  private AmqpTemplate amqpTemplate;

  @Override
  public PageResult<SpuBo> querySpuByPageAndSort(Integer page, Integer rows, Boolean saleable,
      String key) {
    // 1、查询SPU
    // 分页,最多允许查100条
    PageHelper.startPage(page, Math.min(rows, 100));
    // 创建查询条件
    Example example = new Example(Spu.class);
    Example.Criteria criteria = example.createCriteria();
    // 是否过滤上下架
    if (saleable != null) {
      criteria.orEqualTo("saleable", saleable);
    }
    // 是否模糊查询
    if (StringUtils.isNotBlank(key)) {
      criteria.andLike("title", "%" + key + "%");
    }
    Page<Spu> pageInfo = (Page<Spu>) this.spuMapper.selectByExample(example);

    List<SpuBo> list = pageInfo.getResult().stream().map(spu -> {
      // 2、把spu变为 spuBo
      SpuBo spuBo = new SpuBo();
      // 属性拷贝
      BeanUtils.copyProperties(spu, spuBo);

      // 3、查询spu的商品分类名称,要查三级分类
      List<String> names = this.categoryService.queryNameByIds(
          Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
      // 将分类名称拼接后存入
      spuBo.setCname(StringUtils.join(names, "/"));

      // 4、查询spu的品牌名称
      Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
      spuBo.setBname(brand.getName());
      return spuBo;
    }).collect(Collectors.toList());

    return new PageResult<>(pageInfo.getTotal(), list);
  }

  @Override
  @Transactional
  public void save(SpuBo spu) {

    //添加商品要添加四个表 spu, spuDetail, sku, stock四张表
    spu.setSaleable(true);
    spu.setValid(true);
    spu.setCreateTime(new Date());
    spu.setLastUpdateTime(spu.getCreateTime());
    this.spuMapper.insert(spu);
    //保存spu详情插入spuDetail数据
    SpuDetail spuDetail = spu.getSpuDetail();
    spuDetail.setSpuId(spu.getId());
    int count = spuDetailMapper.insert(spuDetail);
    if (count != 1) {
      throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
    }
    //插入sku和库存
    saveSkuAndStock(spu);
    //发送消息
    this.sendMessage(spu.getId(), "insert");
  }


  @Override
  public SpuDetail querySpuDetailById(Long id) {
    return this.spuDetailMapper.selectByPrimaryKey(id);
  }

  @Override
  public List<Sku> querySkuBySpuId(Long spuId) {
    // 查询sku
    Sku record = new Sku();
    record.setSpuId(spuId);
    List<Sku> skus = this.skuMapper.select(record);
    for (Sku sku : skus) {
      // 同时查询出库存
      sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
    }
    return skus;
  }

  @Override
  @Transactional
  public void update(SpuBo spu) {
    //更新数据库  spu
    spu.setLastUpdateTime(new Date());
    spu.setSubTitle("华为p10 4800万超广角AI四摄 3200W美颜自拍 麒麟980全网通版8GB+128GB 幻影蓝 移动联通电信4G全面屏手机");
    int count = spuMapper.updateByPrimaryKeySelective(spu);
    if (count == 0) {
      throw new LyException(ExceptionEnum.GOODS_UPDATE_ERROR);
    }
    /*
    if (spu.getId() == 0) {
      throw new LyException(ExceptionEnum.INVALID_PARAM);
    }
    //首先查询sku
    Sku sku = new Sku();
    sku.setSpuId(spu.getId());
    List<Sku> skuList = skuMapper.select(sku);
    // 如果以前存在，则删除
    if (!CollectionUtils.isEmpty(skuList)) {
      //删除所有sku
      skuMapper.delete(sku);
      //删除库存
      List<Long> ids = skuList.stream()
          .map(Sku::getId)
          .collect(Collectors.toList());
      stockMapper.deleteByIdList(ids);
    }
    //更新数据库  spu
    spu.setLastUpdateTime(new Date());
    int count = spuMapper.updateByPrimaryKeySelective(spu);
    if (count == 0) {
      throw new LyException(ExceptionEnum.GOODS_UPDATE_ERROR);
    }
    // 更新spu详情
    SpuDetail spuDetail = spu.getSpuDetail();
    spuDetail.setSpuId(spu.getId());
    count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
    if (count == 0) {
      throw new LyException(ExceptionEnum.GOODS_UPDATE_ERROR);
    }
    //更新sku和stock
    saveSkuAndStock(spu);*/

    //发送消息
    sendMessage(spu.getId(), "update");
  }

  @Override
  public Spu querySpuById(Long id) {
    return this.spuMapper.selectByPrimaryKey(id);
  }

  /**
   * 保存sku和库存
   */
  private void saveSkuAndStock(SpuBo spu) {
    List<Sku> skuList = spu.getSkus();
    List<Stock> stocks = new ArrayList<>();

    for (Sku sku : skuList) {
      sku.setSpuId(spu.getId());
      sku.setCreateTime(new Date());
      sku.setLastUpdateTime(sku.getCreateTime());
      int count = skuMapper.insert(sku);
      if (count != 1) {
        throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
      }

      Stock stock = new Stock();
      stock.setSkuId(sku.getId());
      stock.setStock(sku.getStock());
      stocks.add(stock);
    }
    //批量插入库存数据
    int count = stockMapper.insertList(stocks);
    if (count == 0) {
      throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
    }
  }

  private void sendMessage(Long id, String type) {
    // 发送消息
    try {
      this.amqpTemplate.convertAndSend("leyou.item.exchange","item." + type, id);
    } catch (Exception e) {
      LOGGER.error("{}商品消息发送异常，商品id：{}", type, id, e);
    }
  }

  @Override
  public Sku querySkuById(Long id) {
    return this.skuMapper.selectByPrimaryKey(id);
  }
}

